<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期">
        <el-date-picker
          v-model="queryParams.weekNumber"
          @change="handleQuery"
          @clear="handleQuery"
          align="right"
          type="date"
          placeholder="选择日期"
          format="yyyyMMdd"
          value-format="yyyyMMdd"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="套餐ID" prop="setmealId">
        <el-input
          v-model="queryParams.setmealId"
          placeholder="请输入套餐ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['canteen:weekly_setmeal:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['canteen:weekly_setmeal:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['canteen:weekly_setmeal:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['system:user:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['canteen:weekly_setmeal:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="weekly_setmealList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="日期" align="center" prop="weekNumber" />
      <el-table-column label="星期" align="center" prop="weekday" />
      <el-table-column label="餐别" align="center" prop="mealType" />
      <el-table-column label="名称" align="center" prop="remark" />
      <el-table-column label="套餐Id" align="center" prop="setmealId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['canteen:weekly_setmeal:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['canteen:weekly_setmeal:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改每周已制定套餐记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="周数" prop="weekNumber">
          <el-input v-model="form.weekNumber" placeholder="请输入周数" />
        </el-form-item>
        <el-form-item label="套餐名称" prop="setmealId">
          <el-select v-model="form.setmealId" placeholder="请选择套餐" style="width: 100%" filterable>
            <el-option
              v-for="item in setmealList"
              :key="item.id"
              :label="`${item.name}(${item.description})`"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="remark">
          <el-select
            v-model="form.remark"
            clearable
            placeholder="请选择分类">
            <el-option
              v-for="item in mealRemark"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 下周菜谱导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess" :auto-upload="false" drag :data="{sheetNumber:upload.sheetNumber}">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-input-number v-model="upload.sheetNumber" :min="1" :max="10" label="描述文字"></el-input-number>
          </div>
          <span>工作表（默认为第一个）,仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWeekly_setmeal, getWeekly_setmeal, delWeekly_setmeal, addWeekly_setmeal, updateWeekly_setmeal ,getSetMealInfo} from "@/api/canteen/weekly_setmeal";
import {getToken} from "../../../utils/auth";

export default {
  name: "Weekly_setmeal",
  data() {
    return {
      setmealList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 每周已制定套餐记录表格数据
      weekly_setmealList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        weekNumber: null,
        weekday: null,
        mealType: null,
        setmealId: null,
        createUser: null,
        updateUser: null,
        remark :null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        weekNumber: [
          { required: true, message: "周数不能为空", trigger: "blur" }
        ],
        weekday: [
          { required: true, message: "星期几不能为空", trigger: "blur" }
        ],
        mealType: [
          { required: true, message: "午餐 or 晚餐不能为空", trigger: "change" }
        ],
        setmealId: [
          { required: true, message: "套餐ID不能为空", trigger: "blur" }
        ]
      },
      mealRemark: [{"id": 1, "name": "套餐A"}, {"id": 2, "name": "套餐B"}, {"id": 3, "name": "套餐C"}],
      dayNumber: new Date(),
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 上传的地址
        url: "http://222.92.47.139:5012" + "/api/v1/uploadWeekMenu",
        //url: "http://127.0.0.1:5012" + "/api/v1/uploadWeekMenu",
        sheetNumber: 1
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
    };
  },
  created() {
    this.getList();
    this.loadSetmealList();
  },
  methods: {
    loadSetmealList() {
      getSetMealInfo().then(res => {
        if (res.code === 200) {
          this.setmealList = res.rows || res.data; // 根据实际返回结构修改
        }
      });
    },
    /** 查询每周已制定套餐记录列表 */
    getList() {
      this.loading = true;
      listWeekly_setmeal(this.queryParams).then(response => {
        this.weekly_setmealList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        weekNumber: null,
        weekday: null,
        mealType: null,
        setmealId: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        remark:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(this.queryParams)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加每周已制定套餐记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWeekly_setmeal(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改每周已制定套餐记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWeekly_setmeal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWeekly_setmeal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除每周已制定套餐记录编号为"' + ids + '"的数据项？').then(function() {
        return delWeekly_setmeal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('canteen/weekly_setmeal/export', {
        ...this.queryParams
      }, `weekly_setmeal_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "周菜单导入";
      this.upload.open = true;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
      this.loadSetmealList();
    },
  }
};
</script>
